<template>
    <div class="input-bar">
      <div class="input-wrapper">
        <!-- 添加隐藏的文件输入框 -->
        <!-- 输入区域 -->
        <textarea 
          class="input" 
          v-model="inputText"
          placeholder="需要我做什么..." 
          :style="{ height: textareaHeight }"
          :disabled="isBlocking"
          @input="onInput"
          @keyup.enter="handleConfirm"
        />

        <!-- 上传文件列表 -->
        <div class="uploaded-files" v-if="uploadedFiles.length > 0">
          <div v-for="(file, index) in uploadedFiles" :key="index" class="file-item">
            <span class="file-name">{{ file.filename }}</span>
            <el-button class="delete-btn" size="small" @click="handleDeleteFile(index,file)">
              <img src="@/assets/icon/close.png" alt="删除" class="delete-icon" />
            </el-button>
          </div>
        </div>

        <!-- 底部功能区 -->
        <div class="bottom-features">
          <div class="feature-buttons">
            <div class="feature-button">
              <el-select 
                v-model="selectedArtifact" 
                @change="selectArtifact" 
                class="no-border min-width"
                :disabled="props.isBlocking"
              >
                <el-option 
                  v-for="artifact in artifacts" 
                  :key="artifact.urn" 
                  :label="artifact.name" 
                  :value="artifact.urn"
                />
              </el-select>
            </div>
            <div class="feature-button" v-if="props.showRagMode">
              <el-select 
                v-model="selectedRagMode" 
                @change="selectRagMode" 
                class="no-border min-width"
                :disabled="props.isBlocking"
                title="召回模式" 
              >
                <el-option 
                  v-for="mode in ragModes" 
                  :key="mode.value" 
                  :label="mode.label" 
                  :value="mode.value"
                />
              </el-select>
            </div>
            <div class="feature-button"  v-if="props.showSearch">
              <img src="@/assets/icon/search.png" alt="search" />
              <span>联网搜索</span>
            </div>
          </div>

          <div class="action-buttons">
            <img 
              class="icon" 
              src="@/assets/icon/history.png" 
              alt="历史" 
              @click="handleHistoryClick" v-if="props.showHistory"
            />
            <img 
              class="icon" 
              src="@/assets/icon/cube.png" 
              alt="cube"  v-if="props.showCube"
            />
            <el-upload
              v-if="props.showUpload"
              ref="uploadRef"
              class="upload-demo"
              :auto-upload="true"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :limit="1"
              :http-request="customUpload"
            >
              <el-tooltip content="上传" placement="top">
                <el-button class="upload-btn" plain>
                  <img src="@/assets/icon/clip.png" class="upload-icon" alt="上传" />
                </el-button>
              </el-tooltip>
            </el-upload>
            <img 
              class="icon" 
              :src="getSendIcon()"
              alt="send"
              :class="hasContent? 'active-icon' : 'inactive-icon'"
              @click="handleClick"
            />
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import sendActiveIcon from '@/assets/icon/send-icon-active.png'
  import sendInActiveIcon from '@/assets/icon/send-icon-inactive-day.png'
  import {MAX_FILE_SIZE} from '@/config'
  import { ElMessage } from 'element-plus'
  import { Resource, GetResourceRequest, DeleteResourceRequest, CreateResourceRequest } from '@/types/proto/api/v1/resource_service'
  import { CreateResource, DeleteResource } from '@/api/resource'

  const uploadedFiles = ref<Resource[]>([]);

  const props = defineProps<{
    isBlocking: boolean
    showRagMode: boolean
    showHistory:boolean
    isVoiceMode: boolean
    showUpload: boolean
    showCube: boolean
    showSearch: boolean
    artifacts: Array<{ urn: string; name: string }>
    selectedArtifact: string
  }>()
  
  const emit = defineEmits<{
    // (e: 'send', text: string, isVoice?: boolean): void
    (e: 'send', text: string): void
    (e: 'voice-result', text: string): void
    (e: 'toggle-mode'): void
    (e: 'stop-all'): void
    (e: 'select-artifact', urn: string): void
    (e: 'select-rag-mode', mode: string): void
    (e: 'history-click'): void
    (e: 'file-change', files: Resource[]): void
  }>()
  
  const inputText = ref('')
  const textareaHeight = ref('36px')
  const isPressed = ref(false)
  const selectedArtifact = ref<string>(props.selectedArtifact)
  const selectedRagMode = ref<string>('NAIVE')
  const hasContent = computed(() => inputText.value.trim().length > 0)
  const uploadRef = ref()

  const ragModes = ref([
    { value: 'NAIVE', label: '向量数据库' },
    { value: 'KG', label: '向量库+知识图谱' }
  ])

  // const fileInput = ref<HTMLInputElement | null>(null)

  const getSendIcon = () => {
    console.log('hasContent:', hasContent.value); 
    return hasContent.value ? sendActiveIcon : sendInActiveIcon
  }
  
  const onInput = (event: Event) => {
    const target = event.target as HTMLTextAreaElement
    textareaHeight.value = `${Math.max(36, target.scrollHeight)}px`
  }
  
  const sendMessage = () => {
    if (hasContent.value) {
      emit('send', inputText.value)
      inputText.value = ''
      textareaHeight.value = '36px'
    }
  }
  
  const handleConfirm = (event: KeyboardEvent) => {
    if (!event.shiftKey) {
      event.preventDefault()
      sendMessage()
    }
  }

  const beforeUpload = (file: File) => {
    if (file.size > MAX_FILE_SIZE) {
      ElMessage.error('文件大小不能超过100MB')
      return false
    }
    return true
  }

  const handleUploadSuccess = () => {
    ElMessage.success('文件上传成功')
    uploadRef.value?.clearFiles()
  }

  const handleUploadError = (error: any) => {
    console.error('Error uploading file:', error)
    ElMessage.error('文件上传失败')
  }

  const handleDeleteFile = (index: number, f:Resource) => {
    uploadedFiles.value.splice(index, 1);
    let r = {urn:f.urn} as DeleteResourceRequest
    DeleteResource(r)
    emit('file-change', uploadedFiles.value)
  }

  const customUpload = async (options: any) => {
    try {
      const file = options.file
      const fileContent = new Uint8Array(await file.arrayBuffer())
      console.log("doc custom upload file", file)
      let req = {
        filename: file.name, 
        type: file.type,
        content: fileContent
      } as CreateResourceRequest
      console.log("doc custom upload req", req)
      
      let res = await CreateResource(req)
      console.log("doc custom upload res", res)

      if (res == null) {
        return
      } 

      if (res && res.urn) {
        uploadedFiles.value.push(res)
      }

      emit('file-change', uploadedFiles.value)

      options.onSuccess()
    } catch (error) {
      console.error('Error uploading file:', error)
      options.onError(error)
    }
  }
  
  const handleTouchStart = () => {
    if (!props.isBlocking) {
      isPressed.value = true
      // Web版本可以使用MediaRecorder API进行录音
      // 这里需要实现具体的录音逻辑
    }
  }
  
  const handleTouchEnd = () => {
    if (!props.isBlocking && isPressed.value) {
      isPressed.value = false
      // 停止录音并处理结果
    }
  }
  
  const handleTouchCancel = () => {
    if (!props.isBlocking && isPressed.value) {
      isPressed.value = false
      // 取消录音
    }
  }
  
  const handleModeToggle = () => {
    if (!props.isBlocking) {
      emit('toggle-mode')
    }
  }
  
  const handleClick = () => {
    if (props.isBlocking) {
      emit('stop-all')
    } else if (hasContent.value) {
      sendMessage()
      uploadedFiles.value = []
    }
  }
  
  const selectArtifact = () => {
    // selectedArtifact.value = urn
    console.log('selectedArtifact:', selectedArtifact.value)
    emit('select-artifact', selectedArtifact.value)
  }

  const selectRagMode = () => {
    console.log('selectedRagMode:', selectedRagMode.value)
    emit('select-rag-mode', selectedRagMode.value)
  }

  const handleHistoryClick = () => {
    if (!props.isBlocking) {
      emit('history-click')
    }
  }

  watch(() => props.selectedArtifact, (newVal: string) => {
    selectedArtifact.value = newVal
  })
  </script>
  
  <style lang="scss" scoped>
  .input-bar {
    width: 100%;
    padding: 16px;
    background-color: #ffffff;
    display: flex;
    justify-content: center;
  }
  
  .input-wrapper {
    width: 100%;
    max-width: 700px;
    display: flex;
    flex-direction: column;
    background-color: #ffffff;
    border-radius: 12px;
    padding: 16px 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  }
  
  .input {
    flex: 1;
    min-height: 24px;
    font-size: 14px;
    border: none;
    resize: none;
    outline: none;
    padding: 8px 0;
    line-height: 1.5;
    
    &::placeholder {
      color: #999;
    }
  }
  
  .bottom-features {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 12px;
  }
  
  .feature-buttons {
    display: flex;
    gap: 8px;
  }
  
  .feature-button {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 6px 12px;
    background-color: #f5f7fa;
    border-radius: 16px;
    cursor: pointer;
    
    img {
      width: 16px;
      height: 16px;
    }
    
    span {
      font-size: 13px;
      color: #666;
    }
  }
  
  .action-buttons {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .icon {
      width: 24px;
      height: 24px;
      cursor: pointer;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 4px;
      
      &:hover {
        opacity: 1;
      }

      &.active-icon {
        background-color: blue;
        opacity: 1;
      }

      &.inactive-icon {
        background-color: rgba(0, 0, 0, 0.1);
        opacity: 0.6;
      }
    }
  }

  .no-border {
    border: none !important;
    outline: none !important;
    background: transparent;
  }

  .min-width {
    min-width: 100px;
  }

  .upload-icon {
    width: 20px;
    height: 20px;
    vertical-align: middle;
  }

  .upload-btn {
    padding: 8px;
    height: auto;
    background: rgba(0, 0, 0, 0.04);
    border: none;
    
    &:hover {
      background: rgba(0, 0, 0, 0.08);
    }
  }

  .uploaded-files {
    padding: 8px 0;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .file-item {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 4px 8px;
    background-color: #f5f7fa;
    border-radius: 4px;
    font-size: 12px;
  }

  .file-name {
    color: #666;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .delete-btn {
    padding: 2px;
    height: 20px;
    width: 20px;
    min-height: auto;
    border: none;
    background: transparent;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background-color: rgba(0, 0, 0, 0.1);
    }
  }

  .delete-icon {
    width: 12px;
    height: 12px;
    opacity: 0.6;
  }
  </style>